package org.tim.websocket.chat;

import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.tim.es.message.UserPrivateMessageResource;
import org.tim.common.msg.MsgType;
import org.tim.common.msg.TimMessage;
import org.tio.core.ChannelContext;
import org.tio.websocket.common.WsResponse;

import java.time.LocalDateTime;

@Slf4j
public class PrivateAckChatKit implements BeforeChatKit {
    @Autowired
    private UserPrivateMessageResource privateMessageResource;

    @Override
    public boolean isSupport(TimMessage timMessage) {
        return MsgType.ACK.equals(timMessage.getMsgType());
    }

    @Override
    public void beforeChat(WsResponse wsResponse, TimMessage timMessage, ChannelContext channelContext, Promise<TimMessage> promise) {
        synchronized (this) {
            if (Strings.isNotEmpty(timMessage.getId())) {
                var now = LocalDateTime.now();

                var optional = privateMessageResource.findById(timMessage.getId());
                if (optional.isPresent()) {
                    var message = optional.get();
                    message.setAck(Boolean.TRUE);
                    message.setAckAt(now);
                    privateMessageResource.save(message);
                } else {
                    promise.setFailure(new Throwable("Send read msg but msg empty"));
                }
            } else {
                promise.setFailure(new Throwable("Send read msg but msgId empty"));
            }
        }
    }
}
